package de.uniwue.cs.ir.vsr;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.StringTokenizer;
import java.util.Vector;

public class DocumentImpl implements IDocument {
	
	private String id = "";
	private HashMap<String, Vector<Integer>> terms = new HashMap<String, Vector<Integer>>();
	// private Iterator<String> iterator;
	private int size = 0;   // number of terms in the document

	public DocumentImpl(String name) {
		id = name;
	}
	
	@Override
	public Iterator<String> iterator() {
		return terms.keySet().iterator();
	}

	@Override
	public String getId() {
		return id;
	}

	@Override
	public void read(InputStream input) throws IOException {
		
		// reading the content of the file into a string
		BufferedInputStream bis = new BufferedInputStream(input);
	    ByteArrayOutputStream buf = new ByteArrayOutputStream();
	    int result = bis.read();
	    while(result != -1) {
	    	byte b = (byte)result;
	    	buf.write(b);
	    	result = bis.read();
	    }        
	    
	    String str  = new String(buf.toString());
	    	     
	    StringTokenizer st = new StringTokenizer(str);
	    int pos = -1;
	    
	    while (st.hasMoreTokens()) {

	    	String tok = st.nextToken();
	    	++pos;
	    	++size;
	    	
	    	if(terms.containsKey(tok)) {   // the term is already in the hash map 
	    		terms.get(tok).add(pos);
	    		
	    	} else {   // the term comes up for the first time
	    		Vector<Integer> positions = new Vector<Integer>();
	    		positions.add(new Integer(pos));
	    		terms.put(tok, positions);
	    	}
	    }
	    
	    // iterator = terms.keySet().iterator();
	}

	@Override
	public int getTermCount(String term) {
		if(terms.containsKey(term)) {
			return terms.get(term).size();
		} else {
			return 0;
		}
	}

	@Override
	public Vector<Integer> getTermPositions(String term) {
		if(terms.containsKey(term)) {
			return terms.get(term);
		} else {
			return new Vector<Integer>();
		}
	}

	@Override
	public String toString() {
		String str = new String("[ ");
		
		Iterator itr = iterator(); 
		while(itr.hasNext()) {

		    String key = (String) itr.next();
		    str = str + key + " -> " + terms.get(key).size() + ", ";

		}
		
		str = str + "]";
		return str;
	}
	
	@Override
	public int size() {
		return size;
	}

}
